package com.eco.fanliapp.job.pddOrderJob;
import com.alibaba.fastjson.JSONObject;
import com.eco.fanliapp.pinduoduo.PDDConfig;
import com.eco.fanliapp.service.IPddOrderInfoService;
import com.eco.fanliapp.utils.HttpUtils;
import com.eco.fanliapp.utils.JsonUtils;
import com.eco.fanliapp.utils.SignMD5Util;
import com.eco.fanliapp.vo.respone.OrderListGetResponse;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.Serializable;
import java.util.TreeMap;

/**
 * @date 2020-03-12
 * 拼多多订单处理
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
@Slf4j
public class PddOrderHandleTask implements Job, Serializable {
    @Autowired
    private IPddOrderInfoService iPddOrderInfoService;
    @Override
    public void execute(JobExecutionContext context) {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();
        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime = System.currentTimeMillis();
        log.info("***************************************开始执行拼多多订单批量处理定时扫描任务-MeiTuanOrderTask：executeCount=" + executeCount + "--startTime=" + startTime);
        Boolean order_get = true;
        Integer page = 1;
        JSONObject object = null;
        String urlNew = "";
        //开始时间、结束时间
        String timestamp = String.valueOf(startTime / 1000);
        Long orderStartTime = (startTime-1000*60*20)/1000;
        Long orderEndTime = startTime / 1000;
        TreeMap<String, String> treeMap = new TreeMap<>();
        treeMap.put("client_id", PDDConfig.PDD_CLIENT_ID);
        treeMap.put("data_type", PDDConfig.PDD_DATA_TYPE);
        treeMap.put("timestamp", timestamp);
        treeMap.put("end_update_time", orderEndTime.toString());
        treeMap.put("start_update_time", orderStartTime.toString());
        treeMap.put("page_size", PDDConfig.PDD_PAGE_SIZE);
        treeMap.put("type", PDDConfig.PDD_ORDER_TYPE);
        treeMap.put("page", page.toString());
        String sign = SignMD5Util.getPDDSignStr(treeMap, PDDConfig.PDD_CLIENT_SECRET);

        StringBuilder url = new StringBuilder(PDDConfig.PDD_HOME_URL);
        url = url.append("?type=").append(PDDConfig.PDD_ORDER_TYPE)
                .append("&data_type=").append(PDDConfig.PDD_DATA_TYPE)
                .append("&timestamp=").append(timestamp)//秒级时间戳
                .append("&client_id=").append(PDDConfig.PDD_CLIENT_ID)
                .append("&start_update_time=").append(orderStartTime)
                .append("&end_update_time=").append(orderEndTime)
                .append("&page_size=").append(PDDConfig.PDD_PAGE_SIZE);
        String pddResponse = "error";
        try {
            urlNew = url.toString()+"&page="+page+"&sign="+sign;
            pddResponse = HttpUtils.sendGet(urlNew, "");
        } catch (Exception e) {
            log.info("拼多多订单拉取异常***");
        }
        object = JSONObject.parseObject(pddResponse);
        String orderList = object.getString("order_list_get_response");
        OrderListGetResponse response = JSONObject.parseObject(orderList, OrderListGetResponse.class);
        if (response != null && response.getOrderList() != null && response.getOrderList().size() > 0) {
            //处理订单
            log.info("处理订单{}",orderList);
            iPddOrderInfoService.handlePddOrder(response.getOrderList());
            //循环拉取下一页
            while (order_get){
                page++;
                treeMap.put("page",page.toString());
                String signtwo = SignMD5Util.getPDDSignStr(treeMap, PDDConfig.PDD_CLIENT_SECRET);
                try {
                    urlNew = url.toString()+"&page="+page+"&sign="+signtwo;
                    pddResponse = HttpUtils.sendGet(urlNew, "");
                } catch (Exception e) {
                    log.info("拼多多订单拉取异常***");
                }
                object = JSONObject.parseObject(pddResponse);
                orderList = object.getString("order_list_get_response");
                response = JSONObject.parseObject(orderList, OrderListGetResponse.class);
                if(response != null && response.getOrderList() != null && response.getOrderList().size() > 0){
                    log.info("处理订单");
                    iPddOrderInfoService.handlePddOrder(response.getOrderList());
                    if(response.getOrderList().size() < 50){
                        order_get = false;
                    }
                }else {
                    order_get = false;
                }
            }
        }
        long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行拼多多订单批量处理定时扫描任务-MeiTuanOrderTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));

    }

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        Boolean order_get = true;
        Integer page = 1;
        JSONObject object = null;
        String urlNew = "";
        //开始时间、结束时间
        String timestamp = String.valueOf(startTime / 1000);
        Long orderStartTime = 1584892800L;
        Long orderEndTime = 1584979200L;
        TreeMap<String, String> treeMap = new TreeMap<>();
        treeMap.put("client_id", PDDConfig.PDD_CLIENT_ID);
        treeMap.put("data_type", PDDConfig.PDD_DATA_TYPE);
        treeMap.put("timestamp", timestamp);
        treeMap.put("end_update_time", orderEndTime.toString());
        treeMap.put("start_update_time", orderStartTime.toString());
        treeMap.put("page_size", PDDConfig.PDD_PAGE_SIZE);
        treeMap.put("type", PDDConfig.PDD_ORDER_TYPE);
        treeMap.put("page", page.toString());
        String sign = SignMD5Util.getPDDSignStr(treeMap, PDDConfig.PDD_CLIENT_SECRET);

        StringBuilder url = new StringBuilder(PDDConfig.PDD_HOME_URL);
        url = url.append("?type=").append(PDDConfig.PDD_ORDER_TYPE)
                .append("&data_type=").append(PDDConfig.PDD_DATA_TYPE)
                .append("&timestamp=").append(timestamp)//秒级时间戳
                .append("&client_id=").append(PDDConfig.PDD_CLIENT_ID)
                .append("&start_update_time=").append(orderStartTime)
                .append("&end_update_time=").append(orderEndTime)
                .append("&page_size=").append(PDDConfig.PDD_PAGE_SIZE);
        String pddResponse = "error";
        try {
            urlNew = url.toString()+"&page="+page+"&sign="+sign;
            pddResponse = HttpUtils.sendGet(urlNew, "");
        } catch (Exception e) {
            log.info("拼多多订单拉取异常***");
        }
        object = JSONObject.parseObject(pddResponse);
        String orderList = object.getString("order_list_get_response");
        OrderListGetResponse response = JSONObject.parseObject(orderList, OrderListGetResponse.class);
        if (response != null && response.getOrderList() != null && response.getOrderList().size() > 0) {
            //处理订单
            log.info("处理订单{}",pddResponse);
//            iPddOrderInfoService.handlePddOrder(response.getOrderList());
            //循环拉取下一页
            while (order_get){
                page++;
                treeMap.put("page",page.toString());
                String signtwo = SignMD5Util.getPDDSignStr(treeMap, PDDConfig.PDD_CLIENT_SECRET);
                try {
                    urlNew = url.toString()+"&page="+page+"&sign="+signtwo;
                    pddResponse = HttpUtils.sendGet(urlNew, "");
                } catch (Exception e) {
                    log.info("拼多多订单拉取异常***");
                }

                response = JsonUtils.getJsonToBean(pddResponse, OrderListGetResponse.class);
                if(response != null && response.getOrderList() != null && response.getOrderList().size() > 0){
                    log.info("处理订单");
//                    iPddOrderInfoService.handlePddOrder(response.getOrderList());
                    if(response.getOrderList().size() < 50){
                        order_get = false;
                    }
                }else {
                    order_get = false;
                }
            }
        }
    }
}
